using System;

namespace Framework
{
    public class ConditionalDecorator<T> : Decorator<T>
    {
        private Func<T, TaskStatus> _conditional;
        private bool _shouldReEvaluate;
        private TaskStatus _conditionalStatus;

        public ConditionalDecorator(Func<T, TaskStatus> conditional, bool shouldReEvaluate = true)
        {
            _conditional = conditional;
            _shouldReEvaluate = shouldReEvaluate;
        }

        public override void OnStart(T context)
        {
            base.OnStart(context);
            _conditionalStatus = TaskStatus.Invalid;
        }

        public override void Invalidate()
        {
            base.Invalidate();
            _conditionalStatus = TaskStatus.Invalid;
        }

        public override TaskStatus Update(T context)
        {
            UpdateConditional(context);
            if (_conditionalStatus == TaskStatus.Running)
            {
                return _conditionalStatus;
            }

            if (_conditionalStatus == TaskStatus.Success)
            {
                return child.Tick(context);
            }

            return TaskStatus.Failure;
        }

        public void UpdateConditional(T context, bool forceUpdate = false)
        {
            if (_conditionalStatus == TaskStatus.Invalid || forceUpdate || _shouldReEvaluate)
            {
                _conditionalStatus = _conditional(context);
            }
        }
    }
}